package com.note.app.config;

import com.note.app.mapper.NoteMapper;
import com.note.app.service.SearchService;
import com.note.common.domain.Note;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Elasticsearch初始化器
 * 负责在应用启动时全量同步数据到Elasticsearch
 */
@Component
@Slf4j
public class ElasticsearchInitializer implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private NoteMapper noteMapper;
    
    @Autowired
    @org.springframework.beans.factory.annotation.Qualifier("searchServiceImpl")
    private SearchService searchService;
    
    @Value("${app.elasticsearch.sync-on-startup:false}")
    private boolean syncOnStartup;
    
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (!syncOnStartup) {
            log.info("Elasticsearch启动时同步已禁用，跳过全量同步");
            return;
        }
        
        log.info("开始全量同步数据到Elasticsearch");
        
        try {
            // 从数据库获取所有笔记
            List<Note> allNotes = noteMapper.selectList(null);
            log.info("从数据库获取到{}条笔记记录", allNotes.size());
            
            int successCount = 0;
            int failCount = 0;
            
            for (Note note : allNotes) {
                try {
                    boolean result = searchService.indexNote(note);
                    if (result) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                    
                    // 打印进度
                    if ((successCount + failCount) % 100 == 0) {
                        log.info("Elasticsearch同步进度: 总数={}, 成功={}, 失败={}", 
                                allNotes.size(), successCount, failCount);
                    }
                } catch (Exception e) {
                    log.error("同步笔记到Elasticsearch失败: noteId=" + note.getId(), e);
                    failCount++;
                }
            }
            
            log.info("Elasticsearch全量同步完成: 总数={}, 成功={}, 失败={}", 
                    allNotes.size(), successCount, failCount);
        } catch (Exception e) {
            log.error("全量同步数据到Elasticsearch失败", e);
        }
    }
}